package server.airpi;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

import commons.Manager;

public class Server extends Thread {

	ServerSocket socketserver; //Le serverSocket
	Socket socket; //Le socket du serveur
	int maxClient;
	int nbClient;
	Manager manager;
	boolean running=true;
	
	private static final int port=8082;
	private static Server INSTANCE=null;

	public Server(int maxClient){
			this.maxClient=maxClient;
			this.nbClient = 0;
			socketserver = null;
	}

	public void run(){
		try {
			while(running){
				if(socketserver == null){
					socketserver = new ServerSocket(this.port);
				}
				if(this.nbClient<this.maxClient || this.maxClient == 0){
					System.out.println("Serveur["+new Date()+"] : Waiting for a client");
					socket = socketserver.accept();
					Task t = new Task(this, socket);
					t.start();
					this.nbClient++;
					System.out.println("Serveur["+new Date()+"] : "+nbClient+" client(s) is/are logged in");
				}else{
					socketserver.close();
					socketserver = null;
				}
			}
		}catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Server getInstance(int maxClient){
		if(INSTANCE==null){
			INSTANCE = new Server(maxClient);
		}
		return INSTANCE;
	}
	
	public void logout(){
		this.nbClient--;
		System.out.println("Serveur["+new Date()+"] : a client logged out");
	}

	public void stopThread(){
		try {
			INSTANCE=null;
			this.running=false;
			socket = new Socket(InetAddress.getLocalHost(),8082);
			this.socketserver.close();
		} catch (IOException e) {
			System.err.println("Serveur["+new Date()+"] : Error while trying to stop the server");
		}
	}
}
